package com.weigecoder.warehouse.controller;

import com.weigecoder.warehouse.constant.WarehouseConstants;
import com.weigecoder.warehouse.entity.*;
import com.weigecoder.warehouse.page.Page;
import com.weigecoder.warehouse.service.*;
import com.weigecoder.warehouse.utils.CurrentUser;
import com.weigecoder.warehouse.utils.QiniuUploadUtil;
import com.weigecoder.warehouse.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RequestMapping("/product")
@RestController
public class ProductController {
    @Autowired
    private StoreService storeService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private SupplyService supplyService;
    @Autowired
    private PlaceService placeService;
    @Autowired
    private UnitService unitService;
    @Autowired
    private ProductService productService;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private QiniuUploadUtil qiniuUploadUtil;

    /**
     * 查询所有仓库的url接口/product/store-list
     *
     * 返回值Result对象给客户端响应查询到的List<Store>;
     */
    @RequestMapping("/store-list")
    public Result storeList(){
        //执行业务
        List<Store> storeList = storeService.queryAllStore();
        return Result.ok(storeList);
    }

    /**
     * 查询所有品牌的url接口/product/brand-list
     * 返回值Result对象给客户端响应查询到的List<Brand>;
     */
    @RequestMapping("/brand-list")
    public Result brandList(){
        //执行业务
        List<Brand> brandList = brandService.queryAllBrand();
        return Result.ok(brandList);
    }

    /**
     * 查询所有商品分类树的url接口/product/category-tree
     * 返回值Result对象给客户端响应查询到的所有商品分类树List<ProductType>;
     */
    @RequestMapping("/category-tree")
    public Result categoryTree(){
        //执行业务
        List<ProductType> typeTreeList = productTypeService.allProductTypeTree();
        return Result.ok(typeTreeList);
    }

    /**
     * 查询所有供应商的url接口/product/supply-list
     * 返回值Result对象给客户端响应查询到的List<Supply>;
     */
    @RequestMapping("/supply-list")
    public Result supplyList(){
        //执行业务
        List<Supply> supplyList = supplyService.queryAllSupply();
        return Result.ok(supplyList);
    }

    /**
     * 查询所有产地的url接口/product/place-list
     * 返回值Result对象给客户端响应查询到的List<Place>;
     */
    @RequestMapping("/place-list")
    public Result placeList(){
        //执行业务
        List<Place> placeList = placeService.queryAllPlace();
        return Result.ok(placeList);
    }

    /**
     * 查询所有单位的url接口/product/unit-list
     * 返回值Result对象给客户端响应查询到的List<Unit>;
     */
    @RequestMapping("/unit-list")
    public Result unitList(){
        //执行业务
        List<Unit> unitList = unitService.queryAllUnit();
        return Result.ok(unitList);
    }

    /**
     * 分页查询商品的url接口/product/product-page-list
     * 参数Page对象用于接收请求参数页码pageNum、每页行数pageSize;
     * 参数Product对象用于接收请求参数仓库id storeId、商品名称productName、
     * 品牌名称brandName、分类名称typeName、供应商名称supplyName、产地名称
     * placeName、上下架状态upDownState、是否过期isOverDate;
     * 返回值Result对象向客户端响应组装了所有分页信息的Page对象;
     */
    @RequestMapping("/product-page-list")
    public Result productPageList(Page page, Product product){
        //执行业务
        page = productService.queryProductPage(page, product);
        return Result.ok(page);
    }

    /**
     * 将配置文件的file.upload-path属性值注入给控制器的uploadPath属性,
     * 其为图片上传到项目的目录路径(类路径classes即resources下的static/img/upload);
     */
    // @Value("${file.upload-path}")
    // private String uploadPath;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 上传图片的url接口/product/img-upload
     * 参数MultipartFile file对象封装了上传的图片;
     * @CrossOrigin表示该url接口允许跨域请求;
     */
    @CrossOrigin
    @PostMapping("/img-upload")
    public Result uploadImg(@RequestParam("file") MultipartFile file){
        /*try {
            //拿到图片上传到的目录(类路径classes下的static/img/upload)的File对象
            File uploadDirFile = ResourceUtils.getFile(uploadPath);
            //拿到图片上传到的目录的磁盘路径
            String uploadDirPath = uploadDirFile.getAbsolutePath();
            //拿到图片保存到的磁盘路径
            String fileUploadPath = uploadDirPath + "\\" + file.getOriginalFilename();
            //保存图片
            file.transferTo(new File(fileUploadPath));
            //成功响应
            return Result.ok("图片上传成功！");
        } catch (IOException e) {
            //失败响应
            return Result.err(Result.CODE_ERR_BUSINESS, "图片上传失败！");
        }*/
        try {
            String originalFilename = file.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(lastIndexOf - 1);
            String uploadFileName = UUID.randomUUID()+suffix;
            qiniuUploadUtil.uploadByQiniu(file.getBytes(),uploadFileName );
            /**
             * 给Redis添加key的值  .add添加的就是这个键对应的值
             * 将所有的商品图片上传到redis的set集合中，然后再和保存成功后的图片set集合做差，调用定时任务清理垃圾图片
             */
            redisTemplate.boundSetOps(WarehouseConstants.PRODUCT_IMAGES_RESOURCES).add(uploadFileName);
            //在存一份用于获取图片名称
            redisTemplate.opsForValue().set(WarehouseConstants.UPLOAD_FILENAME_KEY,uploadFileName);
            return Result.ok("图片上传成功！");
        } catch (IOException e) {
            //失败响应
            return Result.err(Result.CODE_ERR_BUSINESS, "图片上传失败！");
        }
    }

    /**
     * 添加商品的url接口/product/product-add
     * @RequestBody Product product将添加的商品信息的json串数据封装到参数Product对象;
     * @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token
     * 将请求头Token的值即客户端归还的token赋值给参数变量token;
     */
    @RequestMapping("/product-add")
    public Result addProduct(@RequestBody Product product,
                             @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){

        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //获取当前登录的用户id,即添加商品的用户id
        int createBy = currentUser.getUserId();
        String fileName = redisTemplate.opsForValue().get(WarehouseConstants.UPLOAD_FILENAME_KEY);
        //如果用户没有上传图片，则用默认的图片
        /*if (!StringUtils.hasText(fileName)){}*/
        product.setCreateBy(createBy);
        product.setImgs(fileName);
        return productService.saveProduct(product);
    }

    /**
     * 修改商品上下架状态的url接口/product/state-change
     * @RequestBody Product product用于接收并封装请求json数据;
     */
    @RequestMapping("/state-change")
    public Result changeProductState(@RequestBody Product product){
        //响应
        return productService.updateProductState(product);
    }

    /**
     * 删除商品的url接口/product/product-list-delete
     */
    @DeleteMapping("/product-list-delete")
    public Result deleteProductListByBatch(@RequestBody List<Integer> productIds){
        return productService.removeProductByBatch(productIds);
    }

    /**
     * 删除商品的url接口/product/product-delete/{productId}
     */
    @RequestMapping("/product-delete/{productId}")
    public Result deleteProduct(@PathVariable Integer productId){
        return productService.deleteProduct(productId);
    }

    /**
     * 修改商品的url接口/product/product-update
     * @RequestBody Product product将请求传递的json数据封装到参数Product对象;
     * @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token
     * 将请求头Token的值即客户端归还的token赋值给参数变量token;
     */
    @RequestMapping("/product-update")
    public Result updateProduct(@RequestBody Product product,
                                @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){

        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //获取当前登录的用户id,即修改商品的用户id
        int updateBy = currentUser.getUserId();
        product.setUpdateBy(updateBy);
        return productService.updateProduct(product);
    }
}
